package com.itheima.web.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.bean.BeanUtil;
import com.itheima.domain.db.Admin;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.web.exception.BusinessException;
import com.itheima.web.interceptor.AdminHolder;
import com.itheima.web.manager.AdminManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@RestController
public class AdminController {

    @Autowired
    private AdminManager adminManager;
    /**
     * 生成验证码
     */
    @GetMapping("/system/users/verification")
    public void createCodeImg(String uuid,HttpServletResponse response) throws IOException {
        //1.生成验证码
        LineCaptcha lineCaptcha = adminManager.createCode(uuid);
        //2.输出给浏览器
        lineCaptcha.write(response.getOutputStream());
    }

    /**
     * 登录
     */
    @PostMapping("/system/users/login")
    public Map login(@RequestBody Map<String,String> requestMap) throws IOException, BusinessException {

        String username = requestMap.get("username");
        String password = requestMap.get("password");
        String verificationCode = requestMap.get("verificationCode");
        String uuid = requestMap.get("uuid");

        String token = adminManager.login(username , password , verificationCode , uuid );
        //构建返回值
        Map map = new HashMap();
        map.put("token" , token);
        return map;
    }


    /**
     * 登录之后 发起的查询用户请求
     */
    @PostMapping("/system/users/profile")
    public Admin findAdminInfo(@RequestHeader("Authorization") String token) throws IOException, BusinessException {

        //解析token
        //前端拿到token后自动的在前面拼接一个前缀  Bearer
        //去掉前端自动携带的前缀
        //token = token.replace("Bearer " , "");
        ////解析token
        //Map map = JwtUtil.parseToken(token);
        ////这个admin只有id和 用户名
        //Admin admin = BeanUtil.mapToBean(map, Admin.class, true);

        return adminManager.findById(AdminHolder.getId());
    }



    @PostMapping("/system/users/logout")
    public Admin logout(@RequestHeader("Authorization") String token) throws IOException, BusinessException {

        //解析token
        //前端拿到token后自动的在前面拼接一个前缀  Bearer
        //去掉前端自动携带的前缀
        token = token.replace("Bearer " , "");


        return adminManager.loginout(token);
    }
}
